/**
 * created  on 26/12/2017.
 */



window.addEventListener("load", function () {
    AdminManageMain.init();
});
function view(id1, id2) {
    $("#myModal").modal('show');
    //alert(id1 + "" + id2);
    var id = id1 + "" + id2;
    if (id.length < 17) {
        id += "0";
    }
    $.get("adminManage/getAdminById", {"id": id},
        function (result) {
            DataForView(result);
        }, "json");
}
function DataForView(data) {

    $("#hr").empty();
    var strStart = '<div class="col-md-2"> <span class="field">';
    var strEnd = '</span> </div>';
    if (data) {
        var roles = data.roles;
        if (roles) {
            for (var i = 0; i < roles.length; i++) {
                if (i == roles.length - 1) {
                    $("#hr").append(strStart + roles[i].name + strEnd);
                } else {
                    $("#hr").append(strStart + roles[i].name + "、" + strEnd);
                }
            }

        } else {
            $("#hr").append(strStart).append("该用户没任何角色").append(strEnd);
        }
    }

}
/**A
 * 整个脚本的初始化入口
 *
 */
const AdminManageMain = {


    init: function () {
        AdminSearchBox.init();
        AdminTableBox.init();
        AdminDate.init();
    }
};
//格式化日期插件
const AdminDate = {
    init: function () {
        $(".form_datetime").datetimepicker({format: 'yyyy-mm-dd hh:ii:ss'});
    }
}
//状态转换
function stringForStatus(type) {
    var temp;
    switch (type) {
        case 'USE':
            temp = "可用";
            break;
        case 'NOT_USE':
            temp = "不可用";
            break;
    }
    return temp;
}
function stringForSex(type) {
    var temp;
    switch (type) {
        case 'M':
            temp = "男";
            break;
        case 'W':
            temp = "女";
            break;
    }
    return temp;
}
const AdminSearchBox = {

    box: null,

    form: null,

    init: function () {
        this.box = document.querySelector("div.box.search-box");
        this.form = this.box.querySelector("form.search-form");

        //事件监听器

        this.form.querySelector("button.btn.search-btn").addEventListener("click", function () {
            AdminSearchBox.search();
        });


    },
    search: function () {
        var form, params;
        form = this.form;
        field0 = form.querySelector("input[name='createStart']");
        field1 = form.querySelector("input[name='createEnd']");
        field2 = form.querySelector("input[name='name']");
        field3 = form.querySelector("input[name='account']");
        field4 = form.querySelector("input[name='email']");
        field5 = form.querySelector("input[name='phone']");
        //field2 = form.querySelector("select[name='status']");
        params = new Params();
        if (field0.value) {
            params.createStart = field0.value;
        }
        if (field1.value) {
            params.createEnd = field1.value;
        }
        if (field2.value) {
            params.name = field2.value;
        }
        if (field3.value) {
            params.account = field3.value;
        }
        if (field4.value) {
            params.email = field4.value;
        }
        if (field5.value) {
            params.phone = field5.value;
        }
        AdminTableBox.refresh(form.action, params);
    }
    , getForm: function () {
        return this.form;
    }


};

/**
 * 负责 Table 的显示逻辑
 */
const AdminTableBox = {


    _url_: null,

    _tableBox_: null,

    _params_: null,

    _overlayDiv_: null,

    _draw_: 0,

    _dataTable_: null,

    _table_: null,


    _language_: {
        processing: "飞速加载中",
        emptyTable: "没有搜索到符合的结果",
        zeroRecord: "没有匹配的结果",
        paginate: {
            first: "首页",
            last: "尾页",
            previous: "上一页",
            next: "下一页"
        },
        select: {
            rows: "%d 行已选择"
        },
        info: "显示 _START_ 至 _END_   共 _TOTAL_ 行",
        lengthMenu: "每页显示 _MENU_ 行",
        search: "过滤:"
    },
    //delete111

    _updateButton_: {
        className: "btn btn-primary Edit disabled onlyOne",
        text: "编辑",
        action: function (e, dt, node, config) {
            AdminTableEventHandler.buttonEdit(e, dt, node, config);
        }
    },

    _deleteButton_: {
        className: "btn btn-primary Edit disabled onlyOne",
        text: "删除",
        action: function (e, dt, node, config) {
            AdminTableEventHandler.buttonDelete(e, dt, node, config);
        }
    },

    _columns_: [
        {
            "searchable": false,
            //"title":"name",
            "className": "id text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.id == "" ? "--" : row.id;
                        break;
                    case 'set':
                        row.name = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "id",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"name",
            "className": "realName text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.name == "" ? "--" : row.name;
                        break;
                    case 'set':
                        row.name = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "name",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"地址",
            "className": "address text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                cellData = row.realName == "" ? "--" : row.realName;
                return cellData;
            },
            "defaultContent": "--",
            "name": "cloudStorageAddress",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"",
            "className": "fileSize text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.idCard == "" ? "--" : row.idCard;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fileSize",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"",
            "className": "fileSize text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.sex == "" ? "--" : stringForSex(row.sex);
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fileSize",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"",
            "className": "fileSize text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.account == "" ? "--" : row.account;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fileSize",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"",
            "className": "fileSize text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.phone == "" ? "--" : row.phone;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fileSize",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"",
            "className": "fileSize text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.email == "" ? "--" : row.email;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fileSize",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"",
            "className": "fileSize text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.credit == "" ? "--" : row.credit;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fileSize",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"",
            "className": "fileSize text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.address == "" ? "--" : row.address;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fileSize",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "localDateTime text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.createTime == "" ? "--" : row.createTime;
                        break;
                    case 'set':
                        row.start_date = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "localDateTime",
            "orderable": false,
            "type": "date"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "localDateTime text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.previousLoginTime == "" ? "--" : row.previousLoginTime;
                        break;
                    case 'set':
                        row.start_date = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "localDateTime",
            "orderable": false,
            "type": "date"

        },
        {
            "searchable": false,
            //"title":"",
            "className": "status text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.status == "" ? "--" : stringForStatus(row.status);
                        break;
                    case 'set':
                        row.extn = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "status",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"",
            "className": "status text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                var str = row.id.toString();
                var len = str.length;
                cellData = "<a href='javascript:void(0)'><span onclick=view(" + str.substr(0, 16) + "," + str.substr(16, len) + ")>查看角色</span></a>";
                return cellData;
            },
            "defaultContent": "--",
            "name": "status",
            "orderable": false,
            "type": "html"
        }
    ],

    init: function () {
        this._tableBox_ = document.querySelector("div.box.table-box");
        this._table_ = this._tableBox_.querySelector("table.table.data-view");
        this._searchIfAdminNoAction_();
    },
    _searchIfAdminNoAction_: function () {
        let task = null, _this;
        _this = this;
        let callBack = function () {
            if (!_this._dataTable_) {
                _this.refresh(
                    AdminSearchBox.getForm().action
                    , new Params()
                );
            }

            if (task) {
                window.clearTimeout(task);
            }
        };

        task = window.setTimeout(callBack, 100);
    },
    /**
     * 第一次搜索时由 refresh 调用.
     * 完成成以下功能:
     * 1.初始化 table
     * 2.初始化 table 事件处理器
     */
    initDataTable: function () {
        let _this;
        _this = this;
        $.fn.dataTable.ext.errMode = 'none';

        let settings = this._getSetting_();
        this._dataTable_ = $(this._table_).DataTable(settings);

        this._dataTable_.on("xhr.dt", function (e, settings, json, xhr) {
            _this._convertJson_(json)
        });
        this._dataTable_.on('select', function (e, dt, type, indexes) {
            AdminTableEventHandler.select(e, dt, type, indexes);
        });
        this._dataTable_.on('deselect', function (e, dt, type, indexes) {
            AdminTableEventHandler.deselect(e, dt, type, indexes);
        });

        AdminTableEventHandler.init(this._tableBox_, this._dataTable_);

    },
    /**
     * 返回 data table 的配置
     ** @private
     */
    _getSetting_: function () {
        return {
            serverSide: true,
            info: true,
            dom: 'lBrtip',
            scrollX: true,
            /* scrollY: "50vh",*/
            autoWidth: false,
            searching: false,
            columns: this._columns_,
            language: this._language_,
            rowId: "id",
            processing: true,
            // scrollCollapse: false,
            buttons: this._getVisibleButton_(),
            //keys: false,
            select: true,
            pagingType: "full_numbers",
            ordering: false,
            ajax: {
                url: this._url_,
                type: "GET",
                data: function (data, settings) {
                    AdminTableBox._data_(data, settings);
                },
                dataSrc: "data.data"
            }
        };
    },
    /**
     *
     * 将服务器返回的 json 进行转换以便 data table 能够显示.
     * 此方法由 DataTable 的  xhr.dt 事件处理器调用.
     * @param jsonResult 要被转换的 json 对象
     * @private
     */
    _convertJson_: function (jsonResult) {
        if (jsonResult.code === "ok") {
            jsonResult.recordsTotal = jsonResult.data.recordsTotal;
            jsonResult.recordsFiltered = jsonResult.data.recordsFiltered;
        }
    },
    /**
     *根据用户拥有的许可返回相应的按钮
     * @private
     */
    _getVisibleButton_: function () {
        let buttons;
        buttons = [];
        buttons.push(this._updateButton_);
        buttons.push(this._deleteButton_);
        return buttons;
    },
    /**
     * 处理发送至服务器的 参数 .
     * 此方法由 DataTable 调用
     * @param data
     * @param settings
     * @private
     */
    _data_: function (data, settings) {
        let first, max;
        for (let key in data) {
            switch (key) {
                case "start":
                    first = data[key];
                    break;
                case "length":
                    max = data[key];
                    break;
                case "":
            }
            delete data[key];
        }
        data.page = first / max + 1;
        data.rows = max;
        $.extend(data, this._params_);
    },
    /**
     * 当 用户点击搜索按钮时调用此方法刷新 table
     * @param url
     * @param params
     */
    refresh: function (url, params) {
        // 先执行
        this._url_ = url;
        this._params_ = params;
        if (!this._dataTable_) {
            this.initDataTable();
        } else {
            this._dataTable_.ajax.url(this._url_).load();
        }
        this.showTableBox();
    },
    showTableBox: function () {
        if (this._tableBox_.classList.contains("hidden")) {
            this._tableBox_.classList.remove("hidden");
        }
    },
    hideTableBox: function () {
        if (!this._tableBox_.classList.contains("hidden")) {
            this._tableBox_.classList.add("hidden");
        }
    },
    getDataTable: function () {
        return this._dataTable_;
    }, refreshCurrentPage: function () {
        this._dataTable_.draw(false);
    }, updateRowData: function (rowIndex, rowData) {
        let row;
        row = this._dataTable_.row(parseInt(rowIndex));
        row.data(rowData);
    }


};

const AdminTableEventHandler = {

    _dataTable_: null,

    _tableBox_: null,

    _table_: null,

    /**
     *
     * 在 data table 初始化后调用
     * @param dataTable
     */
    init: function (tableBox, dataTable) {

        this._dataTable_ = dataTable;
        this._tableBox_ = tableBox;
        this._table_ = dataTable.table().node();

        AdminUpdateEditor.init();
    },

    buttonEdit: function (e, dt, node, config) {
        if (dt.rows({selected: true}).count() === 1) {
            let row;
            row = dt.row({selected: true});
            AdminUpdateEditor.dialogEditor(row)

        }
    },
    buttonDelete: function (e, dt, node, config) {
        let rowDatas;
        rowDatas = dt.rows({selected: true}).data();
        if (rowDatas.length != 1) {
            return;
        }
        //
        this._doDel_(rowDatas);
    },
    _doDel_: function (rowDatas) {
        let params, callBack, _this;
        params = new Params();
        params["id"] = rowDatas[0].id;
        _this = this;
        callBack = function (data) {
            if (data.code === 'ok') {
                $.notify({
                    icon: 'glyphicon glyphicon-leaf',
                    "title": "通知",
                    message: data.msg
                }, {
                    type: "success",
                    mouse_over: "pause",
                    delay: 3000,
                    placement: {
                        align: "center"
                    },
                    animate: {
                        enter: "animated",
                        exit: "animated"
                    }
                });
                // 刷新当前页
                AdminTableBox.getDataTable().draw(false);
            } else {
                BootstrapDialog.alert({
                    "title": '错误',
                    message: data.message,
                    type: BootstrapDialog.TYPE_DANGER,
                    closable: true,
                    draggable: true,
                    buttonLabel: '确认',
                });
            }
        };
        BootstrapDialog.confirm({
            "title": '警告',
            message: "确定要删除用户 [ id=" + rowDatas[0].id + "] 吗?",
            type: BootstrapDialog.TYPE_WARNING,
            closable: true,
            draggable: true,
            btnCancelLabel: '取消',
            btnOKLabel: '确认',
            btnOKClass: 'btn-warning',
            callback: function (result) {
                if (result) {
                    $.post("adminManage/deleteAdmin", params, callBack, "json");
                }
            }
        });
    },
    select: function (e, dt, type, indexes) {
        DataTableUtils.decisionButtonVisible(dt);

    },
    deselect: function (e, dt, type, indexes) {
        DataTableUtils.decisionButtonVisible(dt);
    }

};


const AdminUpdateEditor = {

    _dialogDiv_: null,

    _dialogEditor_: null,

    _form_: null,

    _publicKeyChange_: false,


    /**
     * 在 {@link TypeTableEventHandler#init}  中调用
     */
    init: function () {
        this._dialogDiv_ = document.querySelector("div.modal.edit-dialog.update");
        this._form_ = this._dialogDiv_.querySelector("form.form-edit.update");
    },
    _initDialogEditor_: function () {
        let _this, e, c, d;
        _this = this;

        this._dialogEditor_ = $(this._dialogDiv_).modal({
            show: false,
            keyboard: true,
            backdrop: "static"
        });
        // 提交按钮
        e = this._dialogDiv_.querySelector("div.modal-footer button.btn.submit");
        c = this._dialogDiv_.querySelector("div.modal-header button.close");
        d = this._dialogDiv_.querySelector("div.modal-footer button.btn.cancel");
        c.addEventListener("click", function () {
            $("#rid").empty();
        });
        d.addEventListener("click", function () {
            $("#rid").empty();
        });
        e.addEventListener("click", function () {
            _this.save();
            $("#rid").empty();
        });
    },


    /**
     *
     * @param dt dataTable 对象
     */
    dialogEditor: function (row) {
        if (!this._dialogEditor_) {
            this._initDialogEditor_();
        }
        FormUtils.formInBoxDisabled(this._dialogDiv_, this._form_, false);
        this._initForUpdate_(row);
        this._showDialog_(true);
    },
    _initForUpdate_: function (row) {
        let rowData;
        rowData = row.data();

        //this._form_.reset();


        this._dialogDiv_.querySelector(".modal-title").innerHTML = "更新: 角色";
        this._dialogDiv_.querySelector("#id").value = rowData.id;


        this._dialogDiv_.querySelector("#credit").value = rowData.credit;
        $("#status1 option[value=" + rowData.status + "]").attr("selected", true);
        $("#status1").selectpicker('refresh');

        $.get("roleManage/getRoleIdAndNameList", null,
            function (data) {
                var selects = $("#rid");
                data = data.data.data;
                $.get("adminManage/getAdminById", {"id": rowData.id},
                    function (result) {
                        var roles = result.roles;
                        for (var i = 0; i < data.length; i++) {
                            var k = 0;
                            for (var j = 0; j < roles.length; j++) {
                                if (data[i].id == roles[j].id) {
                                    k++;
                                    selects.append('<option value="' + data[i].id + '" selected="selected">' + data[i].name + '</option>');
                                }
                            }
                            if (k == 0) {
                                selects.append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
                            }
                        }
                        $("#rid").selectpicker('refresh');
                    }, "json");
            }, "json");
    },
    save: function () {
        FormUtils.formInBoxDisabled(this._dialogDiv_, this._form_, true);

        let input, textarea, params, callBack, _this;

        var form = document.querySelector("#editForm");
        var id = form.querySelector("input[name='id']").value;
        var credit = form.querySelector("input[name='credit']").value;
        var status = form.querySelector("select[name='status']").value;
        var rid = $("#rid").val();
        var param = {};

        param.id = id;
        param.name = credit;
        param.status = status;


        _this = this;
        callBack = function (json) {
            _this._saveCallBack_(json);
        };

        $.post(this._form_.action + "?rid=" + rid, param, callBack, "json");

    },

    _saveCallBack_: function (json) {
        this._showDialog_(false);
        FormUtils.formInBoxDisabled(this._dialogDiv_, this._form_, false);

        if (json.code === "ok") {

            this._showUpdateSuccess_(this._getUpdateSuccessMsg_(json));
            let rowIndex;
            AdminTableBox.getDataTable().draw(false);
            rowIndex = this._form_.getAttribute("data-rowIndex");
        } else {

            this._showUpdateFailure_(this._getUpdateFailureMsg_(json));
        }

    },
    _showDialog_: function (show) {
        if (show) {
            this._dialogEditor_.modal("show");
        } else {
            this._dialogEditor_.modal("hide");
        }

    },
    _getUpdateFailureMsg_: function (json) {
        let message;
        message = json.msg;
        if (json.data) {
            message += "<br/>";
            for (var key in json.data) {
                message += key + " : " + json.data[key];
                message += "<br/>";
            }
        }
        return message;
    },
    _getUpdateSuccessMsg_: function (json) {
        let message;
        message = json.msg + '(已刷新本页),<strong class="text-danger">新数据 不一定显示在本页</strong>' + '<br/>';
        return message;
    },
    _showUpdateSuccess_: function (message) {
        $.notify({
            icon: 'glyphicon glyphicon-leaf',
            title: "通知",
            message: message
        }, {
            type: "success",
            mouse_over: "pause",
            delay: 3000,
            placement: {
                align: "center"
            },
            animate: {
                enter: "animated",
                exit: "animated"
            }
        });
    },
    _showUpdateFailure_: function (message) {
        BootstrapDialog.alert({
            title: '错误',
            message: message,
            type: BootstrapDialog.TYPE_DANGER,
            closable: true,
            draggable: true,
            buttonLabel: '确认',
        });
    },
    /**
     *
     * @param isProtected Boolean
     * @private
     */
    _dialogEditorProtected_: function (isProtected) {
        let submitBtn, cancelBtn, editorArray, editor;
        submitBtn = this._dialogDiv_.querySelector("div.modal-footer > button.cancel");
        cancelBtn = this._dialogDiv_.querySelector("div.modal-footer > button.submit");
        if (isProtected) {
            cancelBtn.classList.add("disabled");
            submitBtn.classList.add("disabled");
        } else {
            cancelBtn.classList.remove("disabled");
            submitBtn.classList.remove("disabled");
        }
        editorArray = this._form_.elements;
        for (let i = 0; i < editorArray.length; i++) {
            editor = editorArray[i];
            if (isProtected) {
                if (!editor.hasAttribute("disabled")) {
                    editor.classList.add("disabled");
                }
            } else {
                editor.classList.remove("disabled");
            }
        }

    }
};

